<?php
/**
 * 会员控制器
 * @author maniac
 */
namespace app\manage\controller;

use app\common\model\MemberRoles;
use app\common\service\PointsService;
use app\facade\Members AS MembersFacade;
use app\common\model\Members AS MembersModel;
use think\Db;
use think\Exception;

class Members extends Base
{
    /**
     * 首页补充
     * @param array $data 列表信息
     */
    public function indexAttach($data)
    {
        $this->roles();
    }
    
    /**
     * 添加/编辑补充
     * @param array $info 信息
     */
    public function addAttach($info)
    {
        if (!$info) {
            $role_id = MemberRoles::order('id ASC')->value('id');
        } else {
            $role_id = $info['role_id'];
        }
        $this->assign('role_id', $role_id);
        $this->roles();
    }
    
    /**
     * where 查询条件
     * @return [type] [description]
     */
    public function where()
    {
        $role_id = input('get.role_id/d', 0);
        $keywords   = input('get.keywords', '');
        $startTime       = input('get.start_time/s', '');
        $endTime         = input('get.end_time/s', '');
        $username = input('username','');
        $mobile = input('mobile','');
        $where = [];
        $type = $type = $this->UserType();
        if ($type != 0){
            $stores_id = $this->stores_id();
            $where[] = [
                ["stores_id","eq",$stores_id]
            ];
        }
        if ($role_id) {
            $where = [
                'role_id' => $role_id,
            ];
        }
        if ($username){
            $where[] = [
                ["username","like","%".$username."%"]
            ];
        }
        if ($mobile){
            $where[] = [
                ["mobile","eq",$mobile]
            ];
        }
        if ($keywords) {

            $where[] = [
                ['nickname','like','%'.$keywords.'%']
            ];
        }
        if ($startTime) {
            $where[] = [
                ['create_time', 'egt', strtotime($startTime)],
            ];
        }
        if ($endTime) {
            $where[] = [
                ['create_time', 'lt', strtotime($endTime)],
            ];
        }
        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->assign('keywords',$keywords);
        $this->assign('username',$username);
        $this->assign('mobile',$mobile);
        return $where;
    }
    
    /**
     * 修改会员余额
     */
    public function balanceChange()
    {
        
        $post = input('post.');
        try {
            $result = MembersFacade::balanceChange($post);
            if ($result) {
                return j(0, '修改成功', $result);
            }
            return j(1, '修改失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 获取所有会员角色
     */
    private function roles()
    {
        $roles = MemberRoles::field('id,name')->order('id ASC')->select();
        $this->assign('roles', $roles);
    }
    
    /**
     * 搜索配送员
     */
    public function search()
    {
        $nickname = input('post.nickname/s', '');
        if (!$nickname) {
            return j(1, '请输入昵称');
        }
        $where = [
            ['nickname', 'like', '%'.$nickname.'%'],
        ];
        $data = MembersModel::field('id,nickname')->where($where)->order('id ASC')->select();
        return j(0, 'success', $data);
    }


    /**
     * 1级分销
     */
    public function indexfx1()
    {
        $userid   = input('userid', 1);
        // 当前页数

        $page   = input('get.page/d', 1);
        // 查询条件
        $where[]  = ['parent_id','eq',$userid];
        // 排序条件
        $order  = $this->order();
        // 数据总数
        $count  = \app\common\model\Members::where($where)->count();
        // 每页条数
        $limit  = $this->limit();
        // 分页条件
        $offset = $this->offset($page, $limit);
        // 分页数据
        $data   = \app\common\model\Members::field(true)->where($where)->order($order)->limit($offset)->select();
        // 模板
        $template = $this->indexTemplate();

        // 列表附加
        $this->indexAttach($data);

        return $this->fetch($template, [
            'page'  => $page,
            'count' => $count,
            'limit' => $limit,
            'data'  => $data,
        ]);
    }

    /**
     * 2级分销
     */
    public function indexfx2()
    {
        $userid   = input('userid', 1);

        // 当前页数
        $page   = input('get.page/d', 1);
        // 查询条件
        $where[]  =  ['parent_id','eq',$userid];
        // 排序条件
        $order  = $this->order();
        // 数据总数
        $count  = \app\common\model\Members::where($where)->count();
        // 每页条数
        $limit  = $this->limit();
        // 分页条件
        $offset = $this->offset($page, $limit);
        // 分页数据
        $data   = \app\common\model\Members::field(true)->where($where)->order($order)->limit($offset)->select();
        // 模板
        $template = $this->indexTemplate();

        // 列表附加
        $this->indexAttach($data);

        return $this->fetch($template, [
            'page'  => $page,
            'count' => $count,
            'limit' => $limit,
            'data'  => $data,
        ]);
    }
    //添加或扣除积分
    public function add_and_deduction_points(){
        $member_id = input('id');
        $points = input('points');
        $type = input('type');//类型 0添加 1扣除
        $points = $type ? "-".$points : $points;
        Db::startTrans();
        try {
            //获取当前管理员
            $userid     = session('userid', '', session_prefix());
            //获取管理员类型
            $admin_type = \app\common\model\Users::where("id",$userid)->value('type');
            $status = $admin_type != 2 ? 1 : 0;
            //添加积分记录
            (new PointsService())->SaveMemberPoints($member_id,$points,$status,$userid,$type,"后台操作积分");
            if($status){
                //重算积分
                (new PointsService())->RecalculationMemberPoints($member_id);
                //重算总积分
                (new PointsService())->RecalculationMemberTotalPoints($member_id);
                //重置会员角色等级
                (new PointsService())->ResetMemberRole($member_id);
            }
            Db::commit();
            return j(0,"操作成功");
        } catch (Exception $exception) {
            Db::rollback();
            return j(1,$exception->getMessage());
        }
    }
    //积分明细
    public function points_log(){
        $id = input('id');
        // 当前页数
        $page   = input('get.page/d', 1);
        // 查询条件
        $where[]  = [
            ['member_id','eq',$id],
        ];
        // 排序条件
        $order  = 'created_at desc';
        // 数据总数
        $count  = \app\common\model\PointsLog::where($where)->count();
        // 每页条数
        $limit  = $this->limit();
        // 分页条件
        $offset = $this->offset($page, $limit);
        // 分页数据
        $data   = \app\common\model\PointsLog::field(true)->where($where)->order($order)->limit($offset)->select();
        // 模板
        $template = $this->indexTemplate();
        // 列表附加
        $this->indexAttach($data);

        return $this->fetch($template, [
            'page'  => $page,
            'count' => $count,
            'limit' => $limit,
            'data'  => $data,
        ]);
    }
    //兑换记录
    public function exchange_log(){
        $id = input('id');
        // 当前页数
        $page   = input('get.page/d', 1);
        // 查询条件
        $order = \app\common\model\Orders::where("userid",$id)->field('id')->select()->toArray();
        $order_ids = array_column($order,"id");
        $where[]  = [
            ['order_id','in',$order_ids],
        ];
        // 排序条件
        $order  = 'id desc';
        // 数据总数
        $count  = \app\common\model\OrderGoods::where($where)->count();
        // 每页条数
        $limit  = $this->limit();
        // 分页条件
        $offset = $this->offset($page, $limit);
        // 分页数据
        $data   = \app\common\model\OrderGoods::field(true)->where($where)->order($order)->limit($offset)->select();
        // 模板
        $template = $this->indexTemplate();
        // 列表附加
        $this->indexAttach($data);

        return $this->fetch($template, [
            'page'  => $page,
            'count' => $count,
            'limit' => $limit,
            'data'  => $data,
        ]);
    }
}
